import React, { useState, useEffect } from 'react';
import { Table, Button, List, Avatar, Popconfirm, message } from 'antd';
import { UserOutlined, DeleteOutlined } from '@ant-design/icons';
import { useParams } from 'react-router-dom';
import { ContestParticipant } from '@/types/contest';
import { contestService } from '@/services/contestService';
import dayjs from 'dayjs';
import styles from '../Detail.module.css';

interface ContestParticipantsProps {
  isAdmin?: boolean;
}

const ContestParticipants: React.FC<ContestParticipantsProps> = ({ isAdmin = false }) => {
  const { id } = useParams();
  const [participants, setParticipants] = useState<ContestParticipant[]>([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    fetchParticipants();
  }, [id]);

  const fetchParticipants = async () => {
    if (!id) return;
    
    try {
      setLoading(true);
      const response = await contestService.getParticipants({ contest_id: Number(id) });
      setParticipants(response.data.data || []);
    } finally {
      setLoading(false);
    }
  };

  const handleDeleteParticipant = async (participantId: number) => {
    try {
      await contestService.deleteParticipant(participantId);
      message.success('删除参与者成功');
      fetchParticipants();
    } catch (error) {
      message.error('删除参与者失败');
    }
  };

  return (
    <div className={styles.participantsSection}>
      {isAdmin ? (
        <Table
          columns={[
            {
              title: '用户名',
              dataIndex: ['user_info', 'username'],
              key: 'username',
            },
            {
              title: '加入时间',
              dataIndex: 'join_time',
              key: 'join_time',
              render: (time: string) => dayjs(time).format('YYYY-MM-DD HH:mm:ss'),
            },
            {
              title: '操作',
              key: 'action',
              render: (_: any, record: ContestParticipant) => (
                <Popconfirm
                  title="确定要删除该参赛者吗？"
                  onConfirm={() => handleDeleteParticipant(record.id)}
                  okText="确定"
                  cancelText="取消"
                >
                  <Button type="link" danger icon={<DeleteOutlined />}>
                    删除
                  </Button>
                </Popconfirm>
              ),
            },
          ]}
          dataSource={participants}
          loading={loading}
          rowKey="id"
        />
      ) : (
        <List
          dataSource={participants}
          loading={loading}
          renderItem={(participant) => (
            <List.Item>
              <List.Item.Meta
                avatar={<Avatar icon={<UserOutlined />} />}
                title={participant.user_info.username}
                description={`加入时间：${dayjs(participant.join_time).format('YYYY-MM-DD HH:mm:ss')}`}
              />
            </List.Item>
          )}
        />
      )}
    </div>
  );
};

export default ContestParticipants; 